/* ===================================================================
// All code unless otherwise posted is licensed under the GPL as specified in license.txt
// ===================================================================*/
var gPerFormancingFirstStart = false;
var gPFFBlogThisText = [false];

function performancing() {
    //Prefs System | http://www.xulplanet.com/references/xpcomref/comps/c_preferencesservice1.html
    // usage: this.prefs.getBoolPref('somevalue') which in prefs will be performancing.somevalue;
    this.prefsService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
    this.prefs = this.prefsService.getBranch("performancing.");// Get the "performancing." branch
    
    //Get Elements
    //We get them here, once, to improve performance
    this.performancing_statusbar_panel = document.getElementById("performancing-statusbar-panel");
    this.performancing_sb_button = document.getElementById("performancing-sb-button");
    
    //Localization Strings
    // All ours strings are localizable, strings used in javascript are found here
    this.stringBundle = document.getElementById("performancingstrings");

}

//This is where all the good stuff goes!
performancing.prototype = {
  
  //First thing we do is load prefs.
  init: function() {
    //Get the pref and set defaults
    this.loadPositionPrefs();
    performancingSetPerFormancingPosition();
    this.showHideCM();
    this.showHideSB();
    
    var appcontent = window.document.getElementById("appcontent");
    if (appcontent) {
        if (!appcontent.performancing) {
            appcontent.performancing = true;
            appcontent.addEventListener("DOMContentLoaded", gperformancing.onPageDomLoad, false);
        }
    }
	
	if (!this.prefs.getBoolPref("onetime.welcomePage")) {
		setTimeout(function () { gperformancing.showFirstRun(); }, 1500);
	}
	else if (this.prefs.getCharPref("version") != gScribeFireVersion) {
		setTimeout(function () { gperformancing.showUpgradePage(gScribeFireVersion); }, 1500);
	}
	
	this.prefs.setBoolPref("onetime.welcomePage", true);
	this.prefs.setCharPref("version", gScribeFireVersion);
  },
  
	showUpgradePage : function (version) {
		var browser = getWebBrowser();
		browser.selectedTab = browser.addTab("http://www.scribefire.com/whats-new/" + version.replace(/\./g, "-") + "/");
	},
	
	showFirstRun : function () {
		var browser = getWebBrowser();
		browser.selectedTab = browser.addTab("http://www.scribefire.com/help/firstrun/");
	},

	toggle : function () {
		if (!this.isOpen()) {
			this.open();
		}
		else {
			this.close();
			window.focus();
		}
	},

	open : function () {
		if (!getScribefireWindow()) {
			var displayMode = this.prefs.getIntPref("displayMode");
		
			switch (displayMode) {
				case 1:
					var win = this.launchWindow('chrome://scribefire/content/scribefire.xul');
				break;
				case 2:
					var win = this.launchWindowInTab('chrome://scribefire/content/scribefire.xul');
				break;
				case 0:
					var win = this.openBottomBar();
				default:
				break;
			}
		}
	},
	
	close : function () {
		var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
		var enumerator = windowMediator.getEnumerator("");

		while (enumerator.hasMoreElements()) {
			var win = enumerator.getNext();

			if (win.location == "chrome://scribefire/content/scribefire.xul") {
				win.close();
				return;
			}
			else {
				var splitScreen = win.document.getElementById("perFormancingMidasFrame");
				
				if (splitScreen && splitScreen.getAttribute("src") == 'chrome://scribefire/content/scribefire.xul') {
					win.gperformancing.closeBottomBar();
					return;
				}
			}
		}

		var browserEnumerator = windowMediator.getEnumerator("navigator:browser");

		// Check all of the tabs for ScribeFire
		while (browserEnumerator.hasMoreElements()) {
			var browserInstance = browserEnumerator.getNext().getWebBrowser();

			// Check each tab of this browser instance
			var numTabs = browserInstance.tabContainer.childNodes.length;

			for(var index = 0; index < numTabs; index++) {
				var currentBrowser = browserInstance.getBrowserAtIndex(index);
				if (currentBrowser.currentURI.spec == 'chrome://scribefire/content/scribefire.xul') {
					browserInstance.selectedTab = browserInstance.tabContainer.childNodes[index];

					if (currentBrowser.contentWindow.wrappedJSObject) {
						currentBrowser.contentWindow.wrappedJSObject.close();
						return;
					}

					currentBrowser.contentWindow.close();
					return;
				}
			}
		}
	},
	
	launchWindow: function(xulDoc, name, config) {
		return window.open(xulDoc, '_blank', 'chrome,centerscreen,resizable=yes,titlebar=yes,dependent=no')
	},
  
	launchWindowInTab: function(xulDoc) {
		var browser = getWebBrowser();
		browser.selectedTab = browser.addTab(xulDoc);
		return browser.selectedBrowser.contentWindow.wrappedJSObject;
	},
  
	isOpen: function() {
		return !!getScribefireWindow();
	},
  
	openBottomBar : function() {
		var bottomBar = document.getElementById("performancing-outerbox");
		var performancingSplinter = document.getElementById("performancingSplit");
		var isOnBottom = this.prefs.getBoolPref("display.onbottom");

		if (isOnBottom && !gPerFormancingFirstStart){
			var theContent = document.getElementById("appcontent");
			
			if (theContent) {
				theContent.appendChild(performancingSplinter);
				theContent.appendChild(bottomBar);
			}
			else {
				var win = document.getElementById("messengerWindow");
				var sb = document.getElementById("status-bar");
				
				win.insertBefore(performancingSplinter, sb);
				win.insertBefore(bottomBar, sb);
			}
			
			gPerFormancingFirstStart = true;
		}

		bottomBar.setAttribute('collapsed', false );
		performancingSplinter.setAttribute('collapsed', false );
		document.getElementById("perFormancingMidasFrame").setAttribute("src", "chrome://scribefire/content/scribefire.xul");
		
		if (document.getElementById("perFormancingMidasFrame").contentWindow.wrappedJSObject) {
			return document.getElementById("perFormancingMidasFrame").contentWindow.wrappedJSObject;
		}
		
		return document.getElementById("perFormancingMidasFrame").contentWindow;
	},
	
	closeBottomBar : function() {
		var bottomBar = document.getElementById("performancing-outerbox");
		var performancingSplinter = document.getElementById("performancingSplit");

		bottomBar.setAttribute('collapsed', "true");
		performancingSplinter.setAttribute('collapsed', "true");
		document.getElementById("perFormancingMidasFrame").setAttribute("src", "chrome://scribefire/content/blank.xul");
	},
  	
	onPageDomLoad: function() {
		//Get the pref and set defaults
		try{
			var myIframeWindow = document.getElementById('perFormancingMidasFrame').contentWindow;
			var myIframeWindowDoc = document.getElementById('perFormancingMidasFrame').contentDocument;
			if( myIframeWindowDoc.getElementById('performancing-technorati-tab').getAttribute('selected') == 'true' ){
				myIframeWindow.setTimeout(function () { performancingUI.getPageInfo('technorati'); }, 1000);
			}
			else if( myIframeWindowDoc.getElementById('performancing-delicious-tab').getAttribute('selected') == 'true' ){
				myIframeWindow.setTimeout(function () { performancingUI.getPageInfo('delicious'); }, 1000);
			}
		}catch(e){
		}
	},
  
  //Show or hide the Context Menu depending on pref
  showHideCM: function() {
    try{ //Do 'try' in odd case where XUL hasn't initialized yet
        if(this.prefs.getBoolPref('display.hideContextMenu')){ //
            document.getElementById("context-performancing-sep").hidden = true;
            document.getElementById("context-performancing").hidden = true;
        }else{
            document.getElementById("context-performancing-sep").hidden = false;
            document.getElementById("context-performancing").hidden = false;
        }
    }catch(e){
        
    }
  },

  //Show or hide the status-bar icon depending on pref
  showHideSB: function() {
    try{ //Do 'try' in odd case where XUL hasn't initialized yet
        if(this.prefs.getBoolPref('display.statusbar')){ //
            document.getElementById("performancing-statusbar-panel").hidden = false;
        }else{
            document.getElementById("performancing-statusbar-panel").hidden = true;
        }
    }catch(e){
        
    }
  },
  
  savePositionPrefs: function( ) {
     // Foo
         try {
           this.prefs.setCharPref("position.parent_element_id", gPerFormancingParentElementID);
           this.makeToolbarItem(gPerFormancingParentElementID);
         } 
         catch (err) {
         }
      
         try {
           this.prefs.setCharPref("position.insert_before_element_id", gPerFormancingInsertBeforeElementId);
         } 
         catch (err) {
         }
      
         try {
           this.prefs.setCharPref("position.insert_after_element_id", gPerFormancingInsertAfterElementId);
         } 
         catch (err) {
         }
    },
    
    makeToolbarItem: function( aElement ) {
     var pffStatusBar = document.getElementById("performancing-sb-button");
     if(aElement == "nav-bar" || aElement == "mail-bar" ){
         pffStatusBar.setAttribute("label", "ScribeFire");
         pffStatusBar.setAttribute("class", "performancing-statusbar-button toolbarbutton-1");
      }else{
         pffStatusBar.setAttribute("label", "");
         pffStatusBar.setAttribute("class", "performancing-statusbar-button");
      }
    },
    
    loadPositionPrefs: function() {
         try {
           gPerFormancingParentElementID = this.prefs.getCharPref("position.parent_element_id");
           this.makeToolbarItem(gPerFormancingParentElementID);
         } 
         catch (err) {
           gPerFormancingParentElementID = '';
         }
      
         try {
           gPerFormancingInsertBeforeElementId = this.prefs.getCharPref("position.insert_before_element_id");
         } 
         catch (err) {
           gPerFormancingInsertBeforeElementId = '';
         }
      
         try {
           gPerFormancingInsertAfterElementId = this.prefs.getCharPref("position.insert_after_element_id");
         } 
         catch (err) {
           gPerFormancingInsertAfterElementId = '';
         }
    }
  
}

//Initialize our object.
var gperformancing = null;
function onPerFormancingLoad() {
    try {
        gperformancing = new performancing();
    } catch(e) { alert("Error on performancing init: " + e); }

    gperformancing.init();//Load Prefs
}


//STATUSBUTTON POSITION
// ***Declare Globar Variables for Drag and Drop***
var gPerFormancingCurrentDropTarget = null;
// the id of the DOM element to position PerFormancing at:
var gPerFormancingParentElementID = "";

// the id of the DOM element to insert PerFormancing before
// if equals to the parent ID, insert as the last child:
var gPerFormancingInsertBeforeElementId = "";
// if the insert before fails, try inserting after this one:
var gPerFormancingInsertAfterElementId = "";


//Make sure we load on start-up of browser.
window.addEventListener('load', onPerFormancingLoad, false);